import logging
import okex.account_api as account
import okex.ett_api as ett
import okex.futures_api as future
import okex.lever_api as lever
import okex.spot_api as spot
import okex.swap_api as swap
import json
import time, datetime
from apscheduler.schedulers.blocking import BlockingScheduler

trade_number  = 0.1
buy_rate      = 0.0
sell_rate     = 4.0
coin_pair     = 'EOS-USDT'
base_currency = 'EOS'
quote_currency= 'USDT'
instrument_id = 'EOS-USD-200626'

api_key       = ''
seceret_key   = ''
passphrase    = ''


def Okex_Spot_Trade():
    try:
        print(80 * '- ')
        # 获取Okex现货账户资金,可用于交易资金.
        now = datetime.datetime.now()
        print(now)
        Okex_spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)
        Okex_futureAPI = future.FutureAPI(api_key, seceret_key, passphrase, True)
        Okex_Account_Base = Okex_spotAPI.get_coin_account_info(base_currency)
        Okex_Account_Quote = Okex_spotAPI.get_coin_account_info(quote_currency)
        print('当前币数量:', Okex_Account_Base['available'] + ' ', base_currency + '  ', '当前钱数量:' ,Okex_Account_Quote['available'] + quote_currency)

        # {'frozen': '0', 'hold': '0', 'id': '', 'currency': 'USDT', 'balance': '32091.12613276', 'available': '32091.12613276', 'holds': '0'}

        # 获取Okex现货盘口
        spot_oreder_book = Okex_spotAPI.get_depth(coin_pair)
        okex_spot_asks, okex_spot_bids = float(spot_oreder_book['asks'][0][0]), float(spot_oreder_book['bids'][0][0])
        # print('现货卖价:', okex_spot_asks, '现货买价:', okex_spot_bids)

        # 获取Okex期货盘口
        future_oreder_book = Okex_futureAPI.get_depth(instrument_id, 1)
        okex_future_asks, okex_future_bids = float(future_oreder_book['asks'][0][0]), float(future_oreder_book['bids'][0][0])
        # print('期货卖价:', okex_future_asks, '期货买价:', okex_future_bids)
        print('现货卖价:', okex_spot_asks, '现货买价:', okex_spot_bids, '   ', '期货卖价:', okex_future_asks, '期货买价:', okex_future_bids)

        # 账户资产是否够下单交易.
        Buy_number = float(Okex_Account_Quote['available']) / okex_spot_asks
        Sell_number = float(Okex_Account_Base['available'])
        print('当前可以买的数量:', Buy_number, '当前可以卖的数量:', Sell_number)

        # 计算溢价率.
        rate = (okex_future_bids - okex_spot_bids) / okex_spot_bids * 100.0
        print('当前市场溢价率:', rate, '买入溢价率:', buy_rate, '卖出溢价率:', sell_rate)

        # 判断卖时候币是否足够本次交易.
        if Buy_number >= trade_number:
            print('当前持仓钱大于买入币数量:',Buy_number)
            if rate <= buy_rate:
                print('下单交易,方向买入')
                # Okex_买现货下单!
                Okex_Spot_Trade = Okex_spotAPI.take_order('limit', 'buy', coin_pair, trade_number, price=okex_spot_bids)
                print(Okex_Spot_Trade)
                if Okex_Spot_Trade['result'] == True:
                    print('下单成功')
                    # {'client_oid': '', 'error_code': '', 'error_message': '', 'order_id': '4395035102222336', 'result': True}
                    time.sleep(10)
                    # Okex_查询订单
                    Okex_Spot_Order_info = Okex_spotAPI.get_order_info(Okex_Spot_Trade['order_id'], coin_pair)
                    print(Okex_Spot_Order_info)
                    if Okex_Spot_Order_info['state'] == '0' or Okex_Spot_Order_info['state'] == '1':
                        print('订单等待成交')
                    # {'client_oid': '', 'created_at': '2020-02-15T20:24:08.034Z', 'filled_notional': '0', 'filled_size': '0', 'funds': '', 'instrument_id': 'EOS-USDT', 'notional': '', 'order_id': '4394991486510080', 'order_type': '0', 'price': '3.745', 'price_avg': '0', 'product_id': 'EOS-USDT', 'side': 'buy', 'size': '100', 'state': '0', 'status': 'open', 'timestamp': '2020-02-15T20:24:08.034Z', 'type': 'limit'}
                        # Okex_撤掉订单
                        Okex_Spot_Revoke_order = Okex_spotAPI.revoke_order(Okex_Spot_Trade['order_id'], coin_pair)
                        print(Okex_Spot_Revoke_order)
                        if Okex_Spot_Revoke_order['result'] == True:
                            print('订单撤掉成功')
                        # {'client_oid': '', 'error_code': '', 'error_message': '', 'order_id': '4395035102222336', 'result': True}
                    elif Okex_Spot_Order_info['state'] == '2':
                        print('本次交易订单全部成功')
                else:
                    print('本次交易完成')
            else:
                print('本次交易溢价不满足条件')

        if Sell_number >= trade_number:
            print('当前持仓币大于卖出数量:',Sell_number)
            if rate >= sell_rate:
                print('下单交易,方向卖出')
                # Okex_卖现货下单!
                Okex_Spot_Trade = Okex_spotAPI.take_order('limit', 'sell', coin_pair, trade_number, price=okex_spot_asks)
                print(Okex_Spot_Trade)
                if Okex_Spot_Trade['result'] == True:
                    print('下单成功')
                    # {'client_oid': '', 'error_code': '', 'error_message': '', 'order_id': '4395035102222336', 'result': True}
                    time.sleep(10)
                    # Okex_查询订单
                    Okex_Spot_Order_info = Okex_spotAPI.get_order_info(Okex_Spot_Trade['order_id'], coin_pair)
                    print(Okex_Spot_Order_info)
                    if Okex_Spot_Order_info['state'] == '0' or Okex_Spot_Order_info['state'] == '1':
                        print('订单等待成交')
                        # {'client_oid': '', 'created_at': '2020-02-15T20:24:08.034Z', 'filled_notional': '0', 'filled_size': '0', 'funds': '', 'instrument_id': 'EOS-USDT', 'notional': '', 'order_id': '4394991486510080', 'order_type': '0', 'price': '3.745', 'price_avg': '0', 'product_id': 'EOS-USDT', 'side': 'buy', 'size': '100', 'state': '0', 'status': 'open', 'timestamp': '2020-02-15T20:24:08.034Z', 'type': 'limit'}
                        # Okex_撤掉订单
                        Okex_Spot_Revoke_order = Okex_spotAPI.revoke_order(Okex_Spot_Trade['order_id'], coin_pair)
                        print(Okex_Spot_Revoke_order)
                        if Okex_Spot_Revoke_order['result'] == True:
                            print('订单撤掉成功')
                            # {'client_oid': '', 'error_code': '', 'error_message': '', 'order_id': '4395035102222336', 'result': True}
                    elif Okex_Spot_Order_info['state'] == '2':
                        print('本次交易订单全部成功')
                else:
                    print('本次交易完成')
            else:
                print('本次交易溢价不满足条件')

        else:
            print('等待下一次轮训.')

    except:
        print('连接失败,等待15秒')
        time.sleep(15)

if __name__ == '__main__':
    scheduler = BlockingScheduler()
    scheduler.add_job(Okex_Spot_Trade, trigger='interval', max_instances=10, seconds=2)
    scheduler.start()
